package com.example.aicode.controller;

import com.example.aicode.tool.AiCodeService;
import jakarta.annotation.Resource;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
public class AiController {
    @Resource
    private AiCodeService aiCodeService;

    @PostMapping("/chat")
    public Flux<ServerSentEvent<String>> chat(@RequestBody ChatRequest request){
        if (request == null || request.getMemoryId() == null || request.getMessage() == null || request.getMessage().isBlank()) {
            return Flux.error(new IllegalArgumentException("memoryId 和 message 不能为空"));
        }
        return aiCodeService.chatStream(request.getMemoryId(), request.getMessage())
                .map(chunk -> ServerSentEvent.<String>builder()
                        .data(chunk)
                        .build());
    }

}
